package net.xju3_4.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.xju3_4.common.framework.simplemvc.RequestMapping;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 静态资源访问控制器
 */
@RequestMapping("/images")
public class StaticResourceController {

    /**
     * 访问头像图片
     */
    @RequestMapping("/avatar/*")
    public void getAvatar(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 获取文件名
            String requestURI = req.getRequestURI();
            String fileName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
            
            // 获取项目根目录下的resources目录
            String projectPath = System.getProperty("user.dir");
            String resourcesPath = projectPath + "/src/main/resources/";
            String avatarPath = resourcesPath + "images/avatar/" + fileName;
            
            File file = new File(avatarPath);
            
            if (!file.exists() || !file.isFile()) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            
            // 设置响应头
            String contentType = getContentType(fileName);
            resp.setContentType(contentType);
            resp.setContentLength((int) file.length());
            
            // 读取文件并输出
            try (FileInputStream fis = new FileInputStream(file);
                 OutputStream os = resp.getOutputStream()) {
                
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
            }
            
        } catch (IOException e) {
            e.printStackTrace();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 根据文件扩展名获取Content-Type
     */
    private String getContentType(String fileName) {
        if (fileName == null) {
            return "application/octet-stream";
        }
        
        String extension = fileName.toLowerCase();
        if (extension.endsWith(".jpg") || extension.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (extension.endsWith(".png")) {
            return "image/png";
        } else if (extension.endsWith(".gif")) {
            return "image/gif";
        } else {
            return "application/octet-stream";
        }
    }
}
